package com.wceManage.manage.qiniu.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.wceManage.commons.util.StringUtil;
import com.wceManage.manage.context.GlobalContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import com.wceManage.commons.util.ConfigPropKit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class PutFile {

	String ak = "";
	String sk = ""; // 密钥配置
	String bucketname = ""; // 空间名

	String up_url = "";


	private static Logger LOGGER = LoggerFactory.getLogger(GlobalContext.class);

	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
	
	/**
	 * 获取上传凭证
	 * 
	 * @return
	 */
	private String getUpToken() {
		Auth auth = Auth.create(ak, sk);
		return auth.uploadToken(bucketname, null, 3600, new StringMap().put("insertOnly", 1));
	}

	/**
	 * 上传文件接口
	 * 
	 * @param file
	 *            文件
	 * @param fileType
	 *            文件类型
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> put64image(File file, String fileType) throws Exception {
		
		ak = ConfigPropKit.get("qiniu_ak").toString();
		sk = ConfigPropKit.get("qiniu_sk").toString();
		up_url = ConfigPropKit.get("qiniu_up_url").toString();
		bucketname = ConfigPropKit.get("qiniu_bucketname").toString();
		String show_url = ConfigPropKit.get("qiniu_show_url").toString();
		
		
		String file64="";
		int l=0;
		FileInputStream fis =null;
	
		long fileLength=file.length();
		if((fileLength/1024)>=300) {
			double cutPercent=0.1;
			fis=new FileInputStream(file);
			BufferedImage bufferedImage=ImageIO.read(fis);

			if(!StringUtil.isEmpty(bufferedImage)){
				int width=bufferedImage.getWidth(null);
				int height=bufferedImage.getHeight(null);

				width=(int)(width*(1-cutPercent));
				height=(int)(height*(1-cutPercent));
				BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
				tag.getGraphics().drawImage(bufferedImage, 0, 0, width, height, null); // 绘制缩小后的图

				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				ImageIO.write(tag, "jpg", outputStream);
				l=outputStream.size();
				byte[] bytes =outputStream.toByteArray();

				file64 = Base64.encodeToString(bytes, 0);
			}
		}else{
			l = (int) (file.length());
			byte[] src = new byte[l];
			 fis = new FileInputStream(file);
			fis.read(src);
			file64 = Base64.encodeToString(src, 0);
		}
		
		/*FileInputStream fis = null;
		int l = (int) (file.length());
		byte[] src = new byte[l];
		fis = new FileInputStream(file);
		fis.read(src);
		String file64 = Base64.encodeToString(src, 0);*/
		
		// 上传的文件名
		String fileName = simpleDateFormat.format(new Date()) + "." + fileType;
		// 上传服务器url
		String url = up_url + l + "/key/" + UrlSafeBase64.encodeToString(fileName);

		RequestBody rb = RequestBody.create(null, file64);
		Request request1 = new Request.Builder().url(url).addHeader("Content-Type", "application/octet-stream")
				.addHeader("Authorization", "UpToken " + getUpToken()).post(rb).build();

		OkHttpClient client = new OkHttpClient();
		okhttp3.Response response = client.newCall(request1).execute();
	
		Map<String, Object> result = new HashMap<String, Object>();

		if (response.code() == 200) {
			result.put("code", "1000");
			result.put("url", show_url + fileName);
		} else {
			LOGGER.error(response.toString());
			result.put("code", "1001");
			result.put("url", "上传文件失败，服务器异常");
		}
		// 关闭流
		if(null!=response){
			response.close();
		}
        if (fis != null) {
        	fis.close();
        }
		return result;
	}

	/**
	 * 上传二维码
	 * 
	 * @param data
	 * @param fileType
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> putQrCode(byte[] data, String fileType) throws Exception {

		ak = ConfigPropKit.get("qiniu_ak").toString();
		sk = ConfigPropKit.get("qiniu_sk").toString();
		up_url = ConfigPropKit.get("qiniu_up_url").toString();
		bucketname = ConfigPropKit.get("qiniu_bucketname").toString();
		String show_url = ConfigPropKit.get("qiniu_show_url").toString();

		int l = data.length;
		String file64 = Base64.encodeToString(data, 0);

		// 上传的文件名
		String fileName = simpleDateFormat.format(new Date()) + "." + fileType;
		// 上传服务器url
		String url = up_url + l + "/key/" + UrlSafeBase64.encodeToString(fileName);

		RequestBody rb = RequestBody.create(null, file64);
		Request request1 = new Request.Builder().url(url).addHeader("Content-Type", "application/octet-stream")
				.addHeader("Authorization", "UpToken " + getUpToken()).post(rb).build();

		OkHttpClient client = new OkHttpClient();
		okhttp3.Response response = client.newCall(request1).execute();

		Map<String, Object> result = new HashMap<String, Object>();

		System.out.println(response.code());

		if (response.code() == 200) {
			result.put("code", "1000");
			result.put("url", show_url + fileName);
		} else {
			LOGGER.error(response.toString());
			result.put("code", "1001");
			result.put("url", "生成文件失败，服务器异常");
		}
		// 关闭流
		if(null!=response){
			response.close();
		}
		
		return result;
	}

}
